<template>
  <div>
    <!-- 面包屑 -->
    <el-bread-crumb secondtitle="权限管理" thirdtitle="角色列表"></el-bread-crumb>
    
    <!-- 卡片 -->
    <el-card-comon>
      <template>

        <!-- 按钮 -->
        <el-row>
          <el-col>
            <el-button-com text="添加角色" @click.native="openAddUserDialog"/>
          </el-col>
        </el-row>

        <!-- table -->
        <role-table :roleList="roleList"></role-table>

      </template>
    </el-card-comon>

    <!-- Dialog弹出框组件区 -->
    <role-dialog-add-user />
    <role-editor-user-info-dialog/>
    <role-distribute-dialog></role-distribute-dialog>
  </div>
</template>

<script>
// 组件引入
import ElBreadCrumb from '@/components/common/ElBreadCrumb';
import ElCardComon from '@/components/common/ElCardComon';
import ElButtonCom from '@/components/common/ElButtonCom';
import RoleTable from '@/views/Main/rightList/roleListComponents/RoleTable';
import RoleDialogAddUser from '@/views/Main/rightList/roleListComponents/RoleDialogAddUser';
import RoleEditorUserInfoDialog from '@/views/Main/rightList/roleListComponents/RoleEditorUserInfoDialog';
import RoleDistributeDialog from '@/views/Main/rightList/roleListComponents/RoleDistributeDialog';

//网络请求
import { getAllRole } from '@/network/roleControlRequest';

export default {
  data() {
    return {
      roleList: []
    }
  },
  created() {
    this.getRole(); // 获取Role数据
    this.$bus.$on('getRole', this.getRole);
    this.$bus.$on('resetRole', data => this.resetRole(data));
  },
  destroyed() {
    this.$bus.$off('getRole');
    this.$bus.$off('resetRole');
  },
  methods: {
    async getRole() { // 获取Role数据列表
      const { data, meta } = await getAllRole();
      if (meta.status !== 200) { // 异常
        console.log(meta);
        return this.$message.error('网络请求失败');
      }

      // 数据获取成功
      this.roleList = data;
      // console.log(this.roleList);
      return this.$message.success('数据获取成功');
    },
    openAddUserDialog() { // 开启添加用户dialog组件
      this.$bus.$emit('openDialog', true);
    },
    resetRole({id: userId, retData}) { // 重新给roleList赋值, 避免重新渲染
      // console.log(userId, retData);
      // console.log(this.roleList);
      this.roleList.forEach(item => {
        if (item.id === userId) {
          // console.log(item.id, userId);
          return item.children = retData;
        } 

      })
    }
  },
  components: {
    ElBreadCrumb,
    ElCardComon,
    ElButtonCom,
    RoleTable,
    RoleDialogAddUser,
    RoleEditorUserInfoDialog,
    RoleDistributeDialog
  }
}
</script>

<style lang="scss" scoped>

</style>